package com.crm.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.crm.pojo.Customer;
import com.crm.pojo.PageInfo;
import com.crm.pojo.SysUser;
import com.crm.service.CustomerService;
import com.crm.service.impl.CustomerServiceImpl;

public class CustomerServlet extends HttpServlet {
	CustomerService customerService = new CustomerServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String flag = req.getParameter("flag");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = null;
		if(flag==null) {
			try {
				items = upload.parseRequest(req);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for(FileItem file:items) {
				if(file.isFormField()) {
					if(file.getFieldName().equals("flag")) {
						flag = file.getString("utf-8");
					}
				}
			}
		}
		
		//获取下拉列表内容，跳转新增页面
		if(flag.equals("goadd")) {
			goadd(req,resp);
		}
		//实现新增功能
		if(flag.equals("add")) {
			add(req,resp,items);
		}
		//查询列表
		if(flag.equals("query")) {
			query(req,resp);
		}
		//删除
		if(flag.equals("del")) {
			delete(req,resp);
		}
		//进入修改
		if(flag.equals("goedit")) {
			goedit(req,resp);
		}
		//修改
		if(flag.equals("edit")) {
			edit(req,resp,items);
		}
	}
	
	//提交修改
	private void edit(HttpServletRequest req, HttpServletResponse resp, List<FileItem> items) throws IOException {
		String path=req.getRealPath("/");
		path=path+"\\upload\\";
		File paths=new File(path);
		if(!paths.exists()){
			paths.mkdir();
		}
		String fileName=UUID.randomUUID().toString();
		Customer customer = new Customer();
		for(FileItem file:items){
			if(file.isFormField() && !file.getString("utf-8").equals("")){
				if(file.getFieldName().equals("custId")) {
					customer.setCustId(Integer.parseInt(file.getString("utf-8")));
				}
				if(file.getFieldName().equals("custName")){
					customer.setCustName(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custSource")){
					customer.setCustSource(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custIndustry")){
					customer.setCustIndustry(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custLevel")){
					customer.setCustLevel(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custPhone")){
					customer.setCustPhone(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custMobile")){
					customer.setCustMobile(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custRegion")){
					customer.setCustRegion(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custCorporation")){
					customer.setCustCorporation(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custAddress")){
					customer.setCustAddress(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custZip")){
					customer.setCustZip(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custFax")){
					customer.setCustFax(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custWebsite")){
					customer.setCustWebsite(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custLicence")){
					customer.setCustLicence(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custCapital")){
					customer.setCustCapital(Integer.parseInt(file.getString("utf-8")));
				}
				if(file.getFieldName().equals("custBank")){
					customer.setCustBank(file.getString("utf-8"));
				}
			}else{
				//多媒体组件
				//获取当前这个文件的名称和路径
				String fileNameOld=file.getName();
				if(fileNameOld!=null && !fileNameOld.equals("")) {
					//获取当前上传这个文件的名称
					fileNameOld=fileNameOld.substring(fileNameOld.lastIndexOf("\\")+1, fileNameOld.length());
					//获取文件的后缀
					String suffix=fileNameOld.substring(fileNameOld.lastIndexOf("."), fileNameOld.length());
					//将 存放路径、生成的随机文件名、后缀名组合
					customer.setCustPic("upload//"+fileName+suffix);
					String fileNameNew=path+fileName+suffix;
					//输出
					try {
						file.write(new File(fileNameNew));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		}
		//将客户信息更新
		boolean flag = customerService.updateCustomer(customer);
		if(flag) {
			resp.sendRedirect(req.getContextPath()+"/success.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
		
	}

	//进入修改
	private void goedit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取客户来源
		List<String> custSources = customerService.queryDict("002");
		req.setAttribute("custSources", custSources);
		//获取客户所属行业
		List<String> custIndustry = customerService.queryDict("001");
		req.setAttribute("custIndustrys", custIndustry);
		//获取客户级别
		List<String> custLevel = customerService.queryDict("006");
		req.setAttribute("custLevels", custLevel);
		
		Integer custId = Integer.parseInt(req.getParameter("custId"));
		Map customer = customerService.quertCustomerByCustId(custId);
		req.setAttribute("customer", customer);
		req.getRequestDispatcher("customer/edit.jsp").forward(req, resp);
	}

	//删除
	private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer custId = Integer.parseInt(req.getParameter("custId"));
		boolean flag = customerService.deleteCustomer(custId);
		if(flag) {
			resp.sendRedirect(req.getContextPath()+"/success.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
	}

	//查询列表
	private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String custName = req.getParameter("custName");
		if(custName==null) {
			custName = "";
		}
		Integer pageSize;
		if(req.getParameter("pageSize")!=null) {
			pageSize = Integer.parseInt(req.getParameter("pageSize"));
		}else {
			pageSize = 15;
		}
		Integer pageNumber;
		if(req.getParameter("pageNumber")!=null) {
			pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
		}else {
			pageNumber = 1;
		}
		PageInfo pageCustomer = customerService.queryCustomer(custName,pageSize,pageNumber);
		req.setAttribute("custName", custName);
		req.setAttribute("pageCustomer", pageCustomer);
		req.getRequestDispatcher("customer/list.jsp").forward(req, resp);
	}

	//实现新增功能
	private void add(HttpServletRequest req, HttpServletResponse resp, List<FileItem> items) throws ServletException, IOException {
		String path=req.getRealPath("/");
		path=path+"\\upload\\";
		File paths=new File(path);
		if(!paths.exists()){
			paths.mkdir();
		}
		String fileName=UUID.randomUUID().toString();
		Customer customer = new Customer();
		for(FileItem file:items){
			if(file.isFormField() && !file.getString("utf-8").equals("")){
				if(file.getFieldName().equals("custName")){
					customer.setCustName(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custSource")){
					customer.setCustSource(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custIndustry")){
					customer.setCustIndustry(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custLevel")){
					customer.setCustLevel(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custPhone")){
					customer.setCustPhone(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custMobile")){
					customer.setCustMobile(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custRegion")){
					customer.setCustRegion(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custCorporation")){
					customer.setCustCorporation(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custAddress")){
					customer.setCustAddress(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custZip")){
					customer.setCustZip(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custFax")){
					customer.setCustFax(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custWebsite")){
					customer.setCustWebsite(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custLicence")){
					customer.setCustLicence(file.getString("utf-8"));
				}
				if(file.getFieldName().equals("custCapital")){
					customer.setCustCapital(Integer.parseInt(file.getString("utf-8")));
				}
				if(file.getFieldName().equals("custBank")){
					customer.setCustBank(file.getString("utf-8"));
				}
			}else{
				//多媒体组件
				//获取当前这个文件的名称和路径
				String fileNameOld=file.getName();
				if(fileNameOld!=null && !fileNameOld.equals("")) {
					//获取当前上传这个文件的名称
					fileNameOld=fileNameOld.substring(fileNameOld.lastIndexOf("\\")+1, fileNameOld.length());
					//获取文件的后缀
					String suffix=fileNameOld.substring(fileNameOld.lastIndexOf("."), fileNameOld.length());
					//将 存放路径、生成的随机文件名、后缀名组合
					customer.setCustPic("upload//"+fileName+suffix);
					String fileNameNew=path+fileName+suffix;
					//输出
					try {
						file.write(new File(fileNameNew));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		}
		//将客户信息存放在数据库中
		boolean flag = customerService.insertCustomer(customer);
		if(flag) {
			resp.sendRedirect(req.getContextPath()+"/success.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
	}
	
	//获取下拉列表内容，跳转新增页面
	private void goadd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取客户来源
		List<String> custSources = customerService.queryDict("002");
		req.setAttribute("custSources", custSources);
		//获取客户所属行业
		List<String> custIndustry = customerService.queryDict("001");
		req.setAttribute("custIndustrys", custIndustry);
		//获取客户级别
		List<String> custLevel = customerService.queryDict("006");
		req.setAttribute("custLevels", custLevel);
		//转发跳转至customer/add.jsp
		req.getRequestDispatcher("/customer/add.jsp").forward(req, resp);
	}

	

}
